package com.aaa.controller;

import com.aaa.entity.MyReturn;
import com.aaa.entity.PageSort;
import com.aaa.entity.Userinfo;
import com.aaa.service.DeptService;
import com.aaa.service.UserService;
import com.aaa.utils.MyTools;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.github.pagehelper.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayInputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author ：Teacher陈（86521760@qq.com）
 * @date ：Created in 2022/6/23 9:37
 * @description：用户业务控制器
 * @modified By：
 * @version: 1.0
 */
@Controller
@RequestMapping("user")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;
    @Autowired
    private DeptService deptService;
    MyReturn myReturn = new MyReturn();
    /**
     * @create by: Teacher陈（86521760@qq.com）
     * @description: 跳转到显示所有用户的页面
     * @create time: 2022/6/23 9:51
     * @return String
     */
    @RequestMapping("toShowUserPage.do")
    public String toShowUserPage(){
       /* int a=2/0;*/
        return "showUser";
    }




    @RequestMapping(value = "findAllUser.do",method = RequestMethod.GET)
    @ResponseBody
    public MyReturn findAllUser(PageSort pageSort,@ModelAttribute("ipadress") String ip) {
        System.out.println("获取全局变量ipadress："+ip);
        //userService目标对象，执行findAllUser之前进行增强处理，添加日志
        //获取代理对象
/*        ProxyDynamicInterface<UserService> dynamicInterface = new ProxyDynamicInterface(userService);
        UserService proxyObj = dynamicInterface.getProxyObj();*/
        //使用代理对象执行目标方法

       Page page = userService.findAllUser(pageSort);
      //  Page page = proxyObj.findAllUser(pageSort);

        //获取分页之后的数据
        myReturn.setData(page.getResult());
        //获取总条数
        myReturn.setCount(page.getTotal());
        return super.getSuccessResult(myReturn);
    }
    /**
     * @create by: Fmc
     * @description: 用户名唯一性校验,查找不同名字
     * @create time: 2022/7/15 19:26
     * @param : userinfo
     */
    @RequestMapping(value = "findNoSameName.do",method = RequestMethod.GET)
    @ResponseBody
    public MyReturn findNoSameName(Userinfo userinfo){
        boolean status = userService.findNoSameName(userinfo);
        if (status){
            // 没有重名
            return super.getSuccessResult(myReturn);
        }
        // 有重名
        return super.getFailResult(myReturn);
    }
    /**
     * @create by: Fmc
     * @description: 添加新用户，同步添加中间表tbl_user_role
     * @create time: 2022/7/14 17:10
     * @param : Userinfo userinfo, HttpSession httpSession
     */
    @RequestMapping("addUser.do")
    @ResponseBody
    public MyReturn addUser(Userinfo userinfo, HttpSession httpSession){
        // 从session中获取当前登录用户信息
        Map<String, Object> userInfo = (Map<String, Object>) httpSession.getAttribute("userInfo");
        // 获取创建人，并添加到新的userinfo实体中
        userinfo.setCreateBy(userInfo.get("username")+"");
        // 获取创建时间，并添加到新的userinfo实体中
        Timestamp createTime = Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
        userinfo.setCreateTime(createTime);
        // 赋予默认头像
        userinfo.setAvatar("https://fmcspace.oss-cn-hangzhou.aliyuncs.com/002.webp");
        // 对用户密码加盐加密
        Map<String, String> passwordSalt = MyTools.makePasswordSalt(userinfo.getPassword());
        // 把密文和盐值添加到userinfo实体中
        userinfo.setPassword(passwordSalt.get("password"));
        userinfo.setSalt(passwordSalt.get("salt"));
        // 添加默认状态
        userinfo.setStatus("1");
        // 添加默认删除标记
        userinfo.setDelFlag("1");
        // 添加新用户
        boolean status = userService.addUser(userinfo);
        if (status){
            // 操作成功
            return super.getSuccessResult(myReturn);
        }else {
            // 操作失败
            return super.getFailResult(myReturn);
        }
    }
    /**
     * @create by: Fmc
     * @description: 通过id删除用户（单个和批量通用）(修改状态，不做物理删除)
     * @create time: 2022/7/14 19:18
     * @param : String userid
     */
    @RequestMapping("deleteUser.do")
    @ResponseBody
    public MyReturn deleteUser(String userid){
        // 获取前端传来的用户id，ids.join(",")返回的是字符串，所以需要用string接收
        String useridStr = userid;
        // 把获取到的字符串拆分为 userid数组，分割条件是  逗号
        String[] userids = useridStr.split(",");
        // 删除用户
        boolean status = userService.deleteUserById(userids);
        if (status){
            // 操作成功
            return super.getSuccessResult(myReturn);
        }else {
            // 操作失败
            return super.getFailResult(myReturn);
        }
    }
    /**
     * @create by: Fmc
     * @description: 重置用户密码
     * @create time: 2022/7/14 19:51
     * @param : userinfo
     */
    @RequestMapping("resetPassword.do")
    @ResponseBody
    public MyReturn resetPassword(Userinfo userinfo){
        // 对用户密码加盐加密
        Map<String, String> passwordSalt = MyTools.makePasswordSalt(userinfo.getPassword());
        // 把密文和盐值添加到userinfo实体中
        userinfo.setPassword(passwordSalt.get("password"));
        userinfo.setSalt(passwordSalt.get("salt"));
        // 修改用户信息
        boolean status = userService.resetPassword(userinfo);
        if (status){
            // 操作成功
            return super.getSuccessResult(myReturn);
        }else {
            // 操作失败
            return super.getFailResult(myReturn);
        }
    }
    /**
     * @create by: Fmc
     * @description: 修改用户信息
     * @create time: 2022/7/14 20:37
     * @param : userinfo
     */
    @RequestMapping("updateUser.do")
    @ResponseBody
    public MyReturn updateUser(Userinfo userinfo,HttpSession httpSession){
        // 从session中获取当前登录用户信息
        Map<String, Object> userInfo = (Map<String, Object>) httpSession.getAttribute("userInfo");
        // 获取修改人，并添加到新的userinfo实体中
        userinfo.setUpdateBy(userInfo.get("username")+"");
        // 获取修改时间，并添加到新的userinfo实体中
        Timestamp updateTime = Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
        userinfo.setUpdateTime(updateTime);
        // 修改状态
        if (userinfo.getStatus() != null && userinfo.getStatus() != ""){
            userinfo.setStatus("1");
        }else {userinfo.setStatus("0");}
        // 执行修改语句
        boolean status = userService.updateUser(userinfo);
        if (status){
            // 操作成功
            return super.getSuccessResult(myReturn);
        }else {
            // 操作失败
            return super.getFailResult(myReturn);
        }
    }
    /**
     * 头像上传
     */
    @PostMapping("upload.do")
    @ResponseBody
    public MyReturn upload(MultipartFile xxx, HttpServletRequest request){
        //获取原始文件名
        String filename = xxx.getOriginalFilename();
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tEH1H2dUfqHCDyjLPuq";
        String accessKeySecret = "pgnMJfLqn3aEBLa39totVOlJHdwW2H";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "aaachenjian";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = UUID.randomUUID()+filename;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String src = "https://" + bucketName + "." + endpoint + "/" + objectName;
        Map map = new HashMap();
        map.put("src",src);
        myReturn.setCode(0);
        myReturn.setData(map);
        try {
            //原始文件

            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(xxx.getBytes()));

            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 上传字符串。
            ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (Exception ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        return myReturn;
    }
    /**
     * @create by: Fmc
     * @description: 获取全部部门
     * @create time: 2022/7/19 21:30
     * @param : null
     */
    @GetMapping("queryAllDept.do")
    @ResponseBody
    public MyReturn queryAllDept(){
        myReturn.setData(userService.queryAllDept());
        return myReturn;
    }
    /**
     * @create by: Fmc
     * @description: 通过session域获取当前用户ID，并通过sql语句查找到该用户的信息
     * @create time: 2022/6/29 10:07
     * @return:
     */
    @GetMapping("selectById.do")
    public MyReturn selectById(HttpSession session){
        Map<String, Object> userInfo = (Map<String, Object>) session.getAttribute("userInfo");
        Integer userid = Integer.parseInt(userInfo.get("userid").toString());
        myReturn.setCode(0);
        myReturn.setData(userService.selectById(userid));
        return myReturn;
    }
    /**
     * @create by: Fmc
     * @description: 个人信息修改
     * @create time: 2022/6/29 18:08
     * @return:
     */
    @RequestMapping("updateOneself.do")
    @ResponseBody
    public MyReturn updateOneself(Userinfo userinfo){
        userinfo.setUpdateTime(Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date())));
        userinfo.setUpdateBy(userinfo.getUsername());
        boolean state = userService.updateOneself(userinfo);
        if(state){
            return super.getSuccessResult(myReturn);
        }else{
            return super.getFailResult(myReturn);
        }
    }
}
